package com.smyh.util;

/**
 * @author Administrator
 *
 */
public class StringFormat {
	/**
	 * ASCII转换为16进制
	 * 
	 * @param str
	 * @return
	 */
	public static String stringToHex(String str) {
		char[] chars = str.toCharArray();
		StringBuffer hex = new StringBuffer();
		for (int i = 0; i < chars.length; i++) {
			hex.append(Integer.toHexString((int) chars[i]));
		}
		return hex.toString();
	}

	/**
	 * @param hex
	 * @return 16进制转换为ASCII
	 */
	public static String hexToString(String hex) {
		hex = hex.replaceAll(" ", "");
		StringBuilder sb = new StringBuilder();
		StringBuilder temp = new StringBuilder();
		for (int i = 0; i < hex.length() - 1; i += 2) {
			String output = hex.substring(i, (i + 2));
			int decimal = Integer.parseInt(output, 16);
			sb.append((char) decimal);
			temp.append(decimal);
		}
		return sb.toString();
	}

	
	/**
	 * @param ipString
	 * @return
	 * 字符串转换ip格式字符串
	 */
	public static String stringToIp(String ipString) {
		Long j = Long.valueOf(ipString.replaceAll(" ", ""), 16);
		String j1 = String.format("%08X", j);
		byte[] str2HexStr = HexStrUtil.hexStr2Bytes(j1);
		String s = "";
		for (int i = 0; i < str2HexStr.length; i++) {
			int i1s = str2HexStr[i] & 0xFF;
			s += i1s + ".";
		}
		return s.substring(0, s.length() - 1);
	}
	
	/**
	 * @param s
	 * @return
	 * 将ip格式的字符串转换为Byte[]
	 */
	public static byte[] ipToBytes(String s){
		String[] split = s.split("\\.");
		byte[] bt = new byte[4];
		for (int i = 0; i < split.length && i < bt.length; i++) {
			bt[i] = HexStrUtil.hexStr2Bytes(Integer.toHexString(Integer.valueOf(split[i])))[0];
		}
		return bt;
	}
}
